import os
from dotenv import load_dotenv

# 加载 .env（如果存在）
load_dotenv()

def _get_bool(env_name: str, default: bool = False) -> bool:
    value = os.getenv(env_name)
    if value is None:
        return default
    return str(value).strip().lower() in {"1", "true", "yes", "y", "on"}

# Celery / Redis
REDIS_URL: str = os.getenv("REDIS_URL", "redis://localhost:6379/0")

# 时区 & 城市
TIMEZONE: str = os.getenv("TIMEZONE", "Asia/Shanghai")
CITY_NAME: str = os.getenv("CITY_NAME", "北京")

# 邮件配置
SMTP_HOST: str | None = os.getenv("SMTP_HOST")
SMTP_PORT: int = int(os.getenv("SMTP_PORT", "587"))
SMTP_USERNAME: str | None = os.getenv("SMTP_USERNAME")
SMTP_PASSWORD: str | None = os.getenv("SMTP_PASSWORD")
SMTP_USE_TLS: bool = _get_bool("SMTP_USE_TLS", True)
SMTP_USE_SSL: bool = _get_bool("SMTP_USE_SSL", False)

EMAIL_FROM: str | None = os.getenv("EMAIL_FROM")
EMAIL_TO: str | None = os.getenv("EMAIL_TO")


def validate_email_config() -> None:
    missing: list[str] = []
    for key, val in {
        "SMTP_HOST": SMTP_HOST,
        "SMTP_USERNAME": SMTP_USERNAME,
        "SMTP_PASSWORD": SMTP_PASSWORD,
        "EMAIL_FROM": EMAIL_FROM,
        "EMAIL_TO": EMAIL_TO,
    }.items():
        if not val:
            missing.append(key)

    if SMTP_USE_TLS and SMTP_USE_SSL:
        raise ValueError("SMTP_USE_TLS 与 SMTP_USE_SSL 不能同时为 true")

    if missing:
        raise ValueError(f"缺少邮件配置: {', '.join(missing)}")